package cn.baage.campus.service.impl;


import cn.baage.campus.constant.CacheConstant;
import cn.baage.campus.model.dto.LikeInfo;
import cn.baage.campus.service.LikeService;
import cn.baage.campus.service.RedisService;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

/**
 * @Description: 点赞Service实现
 * @Author: 八阿哥
 * @url: baage.cn
 * @Version: 1.0
 **/
@Service
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class LikeServiceImpl implements LikeService {


    private final MongoTemplate mongoTemplate;
    private final RedisService<Integer> redisService;

    /**
     * 判断点赞数据是否存在
     *
     * @param targetId 目标ID
     * @param userId 用户ID
     * @param type 类型
     * @return 是否存在
     */
    public boolean checkLike(String targetId, String userId, Integer type) {
        // 构建查询条件
        Criteria criteria = Criteria.where("userId").is(userId)
                .and("type").is(type)
                .and("targetId").is(targetId);
        // 创建查询对象并应用查询条件
        Query query = new Query(criteria);
        return mongoTemplate.exists(query, LikeInfo.class);
    }


    /**
     * 点赞
     *
     * @param targetId 点赞对象ID
     * @param userId   用户的ID
     * @param type     点赞对象类型
     */
    public void like(String targetId, String userId, Integer type) {
        boolean isExists = checkLike(targetId, userId, type);
        if (isExists) {
            // 重复点赞
            return;
        }
        // 将点赞记录保存到mongodb
        LikeInfo likeInfo = new LikeInfo();
        likeInfo.setUserId(userId);
        likeInfo.setType(type);
        likeInfo.setTargetId(targetId);
        mongoTemplate.save(likeInfo);
        // 将点赞数保存
        String likeKey = CacheConstant.LIKE_NUM_KEY + type.toString() + ":" + targetId;
        redisService.increment(likeKey, 1L);
    }


    /**
     * 取消点赞
     *
     * @param targetId 点赞对象ID
     * @param userId   用户的ID
     * @param type     点赞对象类型
     */
    public void unlike(String targetId, String userId, Integer type) {
        // 构建查询条件
        Criteria criteria = Criteria.where("userId").is(userId)
                .and("type").is(type)
                .and("targetId").is(targetId);
        // 创建查询对象并应用查询条件
        Query query = new Query(criteria);
        boolean isExists = mongoTemplate.exists(query, LikeInfo.class);
        if (!isExists) {
            // 未点赞
            return;
        }
        // 从MongoDB中删除点赞记录
        mongoTemplate.remove(query, LikeInfo.class);
        // 将点赞数保存
        String likeKey = CacheConstant.LIKE_NUM_KEY + type.toString() + ":" + targetId;
        redisService.decrement(likeKey, 1L);
    }
 
}